package com.mgm.utils;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

public class ParseUrlUtil {
	
	/** 默认utf-8 */
	private final static String DEF_ENCODE = "UTF-8";

	/**
	 * URL解码
	 * @Title: getURLDecoderString   
	 * @Description: TODO(...)   
	 * @param: @param str
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String getURLDecoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLDecoder.decode(str, DEF_ENCODE);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * URL 转码
	 * @Title: getURLEncoderString   
	 * @Description: TODO(...)   
	 * @param: @param str
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String getURLEncoderString(String str) {
		String result = "";
		if (null == str) {
			return "";
		}
		try {
			result = java.net.URLEncoder.encode(str, DEF_ENCODE);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	/**
	 * 正则替换
	 * @Title: replaceUrlParameterReg   
	 * @Description: 用传入的value替换url中当前name所对应的值
	 * @param: @param url
	 * @param: @param name
	 * @param: @param value
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String replaceUrlParameterReg(String url, String name, String value) {  
        if (StringUtils.isNotBlank(url) && StringUtils.isNotBlank(value)) {  
            url = url.replaceAll("(" + name + "=[^&]*)", name + "=" + value);  
        }  
        return url;  
    }
	
	/**
     * 去掉url中的路径，留下请求参数部分
     * @param strURL url地址
     * @return url请求参数部分
     */
	private static String truncateUrlPage(String strURL) {
		String strAllParam = null;
		String[] arrSplit = null;

		strURL = strURL.trim();

		arrSplit = strURL.split("[?]");
		if (strURL.length() > 1) {
			if (arrSplit.length > 1) {
				if (arrSplit[1] != null) {
					strAllParam = arrSplit[1];
				}
			}
		}

		return strAllParam;
	}
	
	/**
	 * 截取url域 （？前面的网址）
	 * @Title: truncateHostUrl   
	 * @Description: TODO(...)   
	 * @param: @param strURL
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static String truncateHostUrl(String strURL) {
		String strAllParam = null;
		String[] arrSplit = null;

		strURL = strURL.trim();

		arrSplit = strURL.split("[?]");
		if (strURL.length() > 1) {
			if (arrSplit.length > 1) {
				if (arrSplit[0] != null) {
					strAllParam = arrSplit[0];
				}
			}
		}

		return strAllParam;
	}

	/**
	 *   
	 * @Title: getUrlParameterReg   
	 * @Description: 完整的get路径，如：http://www.baidu.com?query=xxxxx?client=xxxx 
	 * @param: @param url
	 * @param: @param name
	 * @param: @return      
	 * @return: String      
	 * @throws
	 */
	public static Map<String, String> getUrlParameterReg(String url) {

		String strUrlParam = truncateUrlPage(url);
		
		if (strUrlParam == null) return null;
	
		return toMap(strUrlParam);
	}

	/**
	 * url参数解析
	 * @Title: toMap   
	 * @Description: 只解析url问号后面的部分 
	 * @param: @param paramUrl 例如：id=1&name=a&age=23
	 * @param: @return      
	 * @return: Map<String,String>      
	 * @throws
	 */
	public static Map<String, String> toMap(String paramUrl) {
		Map<String, String> map = new HashMap<>();
		
		String[] arrSplit = paramUrl.split("[&]");
		for (String strSplit : arrSplit) {
			String[] arrSplitEqual = null;
			arrSplitEqual = strSplit.split("[=]");

			// 解析出键值
			if (arrSplitEqual.length > 1) {
				// 正确解析
				map.put(arrSplitEqual[0], arrSplitEqual[1]);
			} else {
				if (arrSplitEqual[0] != null && arrSplitEqual[0].length() > 0) {
					// 只有参数没有值，不加入
					map.put(arrSplitEqual[0], "");
				}
			}
		}
		return map;
	}
	
	public static void main(String[] args) {
//		String str = "https://apptrknow.com/dir/redirect?placement_id=10219&campaign_id=29013123&affid=8732&cid=[cid]&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]";
//		String url = replaceUrlParameterReg(str, "affid", "aff_id123");
//		System.out.println(url);
//		System.out.println(truncateUrlPage(str));
//		toMap("campaign_id=1");
//		System.out.println("==>"+getUrlParameterReg("?&campaign_id=1"));
//		System.out.println("==>"+getUrlParameterReg(str));
		
		String str = "placement_id=10219&campaign_id=29013123&affid=8732&cid=12121212121&uid=1";
		String str2 = "https://apptrknow.com/dir/redirect?x=1&campaign_id=A29013123&affid=8732&cid=123&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]";
		Map<String, String> map = toMap(str);
		Map<String, String> map2 = getUrlParameterReg(str2);
		System.out.println(map2);
		for (String key : map.keySet()) {
			str = replaceUrlParameterReg(str, key, map2.get(key));
		}
		
		String u = "https://apptrknow.com/dir/redirect?placement_id=10219&campaign_id=29013123&affid=8732&cid=[cid]&data1=[data1]&data2=[data2]&data3=[data3]&data4=[data4]&affsub1=[affsub1]&device_id=[device_id]&idfa=[idfa]&gaid=[gaid]&source_app=[source_app]";
		System.out.println(truncateHostUrl(u)+"?"+str);
	}

}
